const express = require('express');
const router = express.Router();
const { Category, Course, Chapter, User } = require('../models');
const { where } = require('sequelize');
const { failure, success } = require('../utils/responses');
const { NotFoundError } = require('../utils/errors');

//查询课程分类列表
router.get('/', async function (req, res) {
    try {
        const query = req.query
        const currentPage = Math.abs(Number(query.currentPage)) || 1
        const pageZize = Math.abs(Number(query.pageZize)) || 10
        const soffset = (currentPage - 1) * pageZize

        if (!query.categoryId) {
            throw new Error('获取课程失败，分类ID不能为空')
        }

        const condition = {
            attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
            where: { categoryId: query.categoryId },
            order: [['id', 'desc']],
            limit: pageZize,
            offset: soffset
        }

        const { count, rows } = await Course.findAndCountAll(condition)

        success(res, '查询课程成功', {
            courses: rows,
            pagination: {
                total: count,
                currentPage,
                pageZize
            }
        })
    } catch (error) {
        failure(res, error)
    }
});

//查询课程详情
router.get('/:id', async function (req, res) {
    try {
        const { id } =req.params
        const condition = {
            attributes: { exclude: ['CategoryId', 'UserId'] },
            include: [
                {
                    model: Category,
                    as: 'category',
                    attributes: ['id', 'name']
                },
                {
                    model: Chapter,
                    as: 'chapters',
                    attributes: ['id', 'title', 'rank', 'createdAt'],
                    order: [['rank', 'ASC'], ['id', 'DESC']]
                },
                {
                    model: User,
                    as: 'user',
                    attributes: ['id', 'username', 'nickname', 'avatar', 'company']
                }
            ]
        }
        const course = await Course.findByPk(id, condition)
        if(!course){
            throw new NotFoundError(`ID为${id}的课程不存在`)
        }

        success(res, '查询课程成功', { course })

    } catch (error) {
        failure(res, error)
    }

})

module.exports = router;
